import openpyxl as xlsx

from .mxlsx_title import XlsxTitle


class Xlsx:
    wb: xlsx.Workbook
    cursor: int
    sheet: any

    def __init__(self, wb: xlsx.Workbook, cursor: int = 1):
        self.cursor = cursor
        self.wb = wb
        self.sheet = wb.active

    def select_sheet(self, sheet_name: str):
        self.sheet = self.wb.get_sheet_by_name(sheet_name)
        self.cursor = 1

    def create_sheet(self, sheet_name: str, index=None):
        self.sheet = self.wb.create_sheet(title=sheet_name, index=index)
        self.cursor = 1

    def load_title(self, row: int) -> XlsxTitle:
        rows = self.sheet[row]
        mapp = {}
        letter_list = []
        for row in rows:
            mapp[row.internal_value] = row.column_letter
            letter_list.append(row.column_letter)
        return XlsxTitle(mapp, letter_list)

    def next_cursor(self):
        self.cursor += 1

    def pre_cursor(self):
        self.cursor -= 1

    def set_cursor(self, cursor: int):
        self.cursor = cursor

    def cell(self, value: any, row: int = None, column: int = None, key: str = None):
        if key is not None:
            self.sheet[key + str(self.cursor)] = value
        elif row is not None and column is not None:
            self.sheet.cell(row, column, value)
        else:
            raise Exception("(row , column and  key) must define one item")

    def value(self, row: int = None, column: int = None, key: str = None):
        if key is not None:
            return self.sheet[key + str(self.cursor)].value
        elif row is not None and column is not None:
            return self.sheet.cell(row=row, column=column)
        else:
            raise Exception("(row , column and  key) must define one item")

    def has_next(self) -> bool:
        return self.sheet.max_row > self.cursor

    def has_pre(self) -> bool:
        return self.cursor > 0

    def writer(self, filename: str):
        self.wb.save(filename)

    def close(self):
        self.wb.close()


def load_workbook(filename: str) -> Xlsx:
    return Xlsx(xlsx.load_workbook(filename))


def create(title: str = None) -> Xlsx:
    x = Xlsx(xlsx.Workbook())
    if title is None:
        return x
    else:
        x.wb.active.title = title
        return x
